<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\others\UploadFileController;
use App\models\forum\Categorie;
use App\models\forum\Moderator;
use App\models\forum\Partition;
use App\models\forum\PartitionCategorie;
use App\models\forum\Replie;
use App\models\forum\Topic;
use App\models\user\User;
use App\other\AdminFlag;
use App\other\UtilsClass;
use Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;

class TopicAdminController extends Controller
{
    private $perPage = 30;
    public function __construct(){
        $this->perPage = env('APP_PAR_PAGE', 30);
        $this->middleware('admin:'.AdminFlag::ADMIN_FLAG_TOPIC_ED);
    }

    public function index(){
        return view('admin.topic');
    }

    public function topics(Request $request){
        $q = $request->get('q');
        if (empty($q)){
            $topics = Topic::where('id', '>', 0)->where('is_delete', 0)->orderby('updated_at', 'DESC')->paginate($this->perPage);
        }else{
            $seach = '%'.$q."%";
            $topics = Topic::where('title', 'like', $seach)->where('is_delete', 0)->orderby('updated_at', 'DESC')->paginate($this->perPage);
        }
        return view('admin.topic.list', compact('topics', 'q'));
    }

    public function del(Request $request){
        $validtor = Validator::make($request->all(),[
            'id' => 'required|integer|exists:topics,id',
        ]);

        if ($validtor->fails()){
            return ['code' => '100', 'msg' => '物品不存在'];
        }

        Topic::where('id',$request->get('id'))->update(['is_delete' => 1, 'deleted_at' => new Carbon, 'chang_user_id' => Auth::id()]);
        return ['code' => '0'];
    }

    public function trash(Request $request){
        $q = $request->get('q');
        if (empty($q)){
            $topics = Topic::where('id', '>', 0)->where('is_delete', 1)->orderby('updated_at', 'DESC')->paginate($this->perPage);
        }else{
            $seach = '%'.$q."%";
            $topics = Topic::where('title', 'like', $seach)->where('is_delete', 1)->orderby('updated_at', 'DESC')->paginate($this->perPage);
        }
        return view('admin.topic.trash', compact('topics', 'q'));
    }

    public function action(Request $request){
        $validtor = Validator::make($request->all(),[
            'action'    => 'required',
            'ids'       => 'required|array',
        ]);

        if ($validtor->fails()){
            return ['code' => '100', 'msg' => '无法操作'];
        }

        $input = $request->all();
        if ($input['action'] = 'restore'){
            Topic::whereIn('id', $input['ids'])->update(['is_delete' => 0, 'deleted_at' => new Carbon, 'chang_user_id' => Auth::id()]);
            return ['code' => 0];
        }elseif ($input['action'] == 'delete'){
            Topic::destroy($input['ids']);
            return ['code' => 0];
        }
        return $this->errorAction();
    }

    public function reply(){
        $replies = Replie::where('id', '>', 0)->orderby('updated_at', 'desc')->paginate(30);
        return view('admin.topic.reply', compact('replies'));
    }

    public function replyAction(Request $request){
        $validator = Validator::make($request->all(),[
            'action'    => 'required',
            'ids'       => 'required|array',
        ]);

        if ($validator->fails()){
            return ['code' => '100', 'msg' => '无法操作'];
        }
        $input = $request->all();
        if ($input['action'] == 'delete'){
            Topic::destroy($input['ids']);
            return ['code' => 0];
        }
        return $this->errorAction();
    }

    public function partitions(Request $request){
        $q = $request->get('q');
        if (empty($q)){
            $partitions = Partition::where('id', '>', 0)->paginate(30);
        }else{
            $seach = '%'.$q."%";
            $partitions = Partition::where('title', 'like', $seach)->paginate(30);
        }
        return  view('admin.topic.partitions', compact('partitions', 'q'));
    }

    public function plateAction(Request $request){
        $validtor = Validator::make($request->all(),[
            'action'    => 'required',
            'ids'       => 'required|array',
        ]);

        if ($validtor->fails()){
            return ['code' => '100', 'msg' => '无法操作'];
        }
        $input = $request->all();if ($input['action'] == 'delete'){
            Partition::destroy($input['ids']);
            return ['code' => 0];
        }
        return $this->errorAction();
    }

    public function getPlate(Request $request){
        $v = Validator::make($request->all(),[
            'id'        => 'required|integer|exists:partitions,id',
        ]);
        if ($v->fails()){
            $this->errorAction();
        }
        return ['code' => 0, 'data' => Partition::find($request->get('id'))];
    }

    public function plateDel(Request $request){
        $v = Validator::make($request->all(), [
            'id'        => 'required|integer|exists:partitions,id',
        ]);
        if ($v->fails()){
            return redirect()->back()->with(['error' => '删除失败']);
        }
        Partition::destroy($request->get('id'));
        return redirect()->back()->with(['success' => '删除成功']);
    }

    public function platePull(Request $request){
        $input = $request->all();
        $v = Validator::make($input, $this->platePullValidator($input));
        if ($v->fails()){
            return redirect()->back()->with('error', UtilsClass::arrayToStringForItem(
                $v->getMessageBag()->getMessages())
            );
        }
        if ($request->has('is_enable')){
            $input['is_enable'] = 1;
        }else{
            $input['is_enable'] = 0;
        }
        if ($request->file('img') != null) {
            $input['img'] = UploadFileController::getImgPateh($request, 'img');
        }elseif (empty($request->get('id'))){
            $input['img'] = '';
        }else{
            unset($input['img']);
        }
        unset($input['_token']);
        unset($input['_method']);
        unset($input['id']);
        if (empty($request->get('id'))){
            Partition::forceCreate($input);
        }else{
            Partition::where('id', $request->get('id'))->update($input);
        }
        return redirect()->back()->with(['success ' => '操作成功']);
    }

    public function plateTags(){
        $categories =  Categorie::all();
        return  view('admin.topic.plate_tags', compact('categories'));
    }

    public function tagsAction(Request $request){
        $validtor = Validator::make($request->all(),[
            'action'    => 'required',
            'ids'       => 'required|array',
        ]);

        if ($validtor->fails()){
            return $this->errorAction();
        }
        $input = $request->all();if ($input['action'] == 'delete'){
            Categorie::destroy($input['ids']);
            return ['code' => 0];
        }
        return $this->errorAction();
    }

    public function tagsGet(Request $request){
        $v = Validator::make($request->all(),[
            'id'        => 'required|integer|exists:categories,id',
        ]);
        if ($v->fails()){
            $this->errorAction();
        }
        return ['code' => 0, 'data' => Categorie::find($request->get('id'))];
    }

    public function tagsPull(Request $request)
    {
        $input = $request->all();
        $v = Validator::make($input, [
            'id'        => 'integer|exists:categories,id',
            'name'      => 'required|max:32',
            'color'     => 'required|max:10',
            'index'     => 'integer',
            'is_enable' => 'max:3'
        ]);
        if ($v->fails()){
            return redirect()->back()->with(
                'error',
                UtilsClass::arrayToStringForItem($v->getMessageBag()->getMessages())
            );
        }
        if ($request->has('is_enable')){
            $input['is_enable'] = 1;
        }else{
            $input['is_enable'] = 0;
        }
        unset($input['_token']);
        unset($input['id']);
        if (empty($request->get('id'))){
            Categorie::forceCreate($input);
        }else{
            Categorie::where('id', $request->get('id'))->update($input);
        }
        return redirect()->back()->with('success ', '操作成功');
    }

    public function plateGetTags(Request $request){
        $vali = Validator::make($request->all(), [
            'id'        => 'required|integer|exists:partitions,id'
        ]);
        if ($vali->fails()){
            return view('errors.404');
        }
        $plate_id          = $request->get('id');
        $plate = Partition::find($plate_id);
        if (!empty($plate) && !empty($plate->partitionCategorie()->get())){
            $partitionCategorie = $plate->partitionCategorie()->get();
        }else{
            $partitionCategorie = null;
        }
        $categorie = Categorie::where('is_enable', 1)->get();
        return view('admin.topic.plate_get_tag', compact('partitionCategorie', 'categorie', 'plate_id'));
    }

    public function plateTagAdd(Request $request){
        $validator = Validator::make($request->all(), [
            'plate_id'      => 'required|integer|exists:partitions,id',
            'id'            => 'required|integer|exists:categories,id'
        ]);

        if ($validator->fails()){
            return redirect()->back()->with('error', UtilsClass::arrayToStringForItem(
                $validator->getMessageBag()->getMessages())
            );
        }
        $input = $request->all();
        if (PartitionCategorie::isHas($input['plate_id'], $input['id'])){
            return redirect()->back()->with('error', '已存在');
        }
        $pc = new PartitionCategorie();
        $pc->pid = $input['plate_id'];
        $pc->cid = $input['id'];
        $pc->save();
        return redirect()->back()->with('success', '添加成功');
    }

    public function plateTagDel(Request $request){
        $validator = Validator::make($request->all(), [
            'id'            => 'required|integer|exists:partition_categories,id'
        ]);
        if ($validator->fails()){
            return ['code' => 200, 'msg' => '删除失败[数据不存在]'];
        }
        PartitionCategorie::destroy($request->get('id'));
        return ['code' => 0];
    }

    public function plateGetAdmins(Request $request){
        $vali = Validator::make($request->all(), [
            'id'        => 'required|integer|exists:partitions,id'
        ]);
        if ($vali->fails()){
            return view('errors.404');
        }
        $plate_id           = $request->get('id');
        $admins             = User::getPlateAdmins($plate_id);
        $userAdmins         = User::getUserByFlag(AdminFlag::ADMIN_FLAG_TOPIC_ED);
        return view('admin.topic.plate_admin', compact('admins', 'userAdmins', 'plate_id'));
    }

    public function modDel(Request  $request){
        $vali = Validator::make($request->all(), [
            'mid'        => 'required|integer|exists:moderators,id'
        ]);
        if ($vali->fails()){
            return $this->errorAction();
        }
        Moderator::destroy($request->get('mid'));
        return ['code' => 0];
    }

    public function modAdd(Request  $request){
        $vali = Validator::make($request->all(), [
            'plate_id'          => 'required|integer|exists:partitions,id',
            'users_id'          => 'required|integer|exists:users,id'
        ]);
        if ($vali->fails()){
            return redirect()->back()->with(
                'error',
                UtilsClass::arrayToStringForItem(
                    $vali->getMessageBag()->getMessages()
                )
            );
        }
        $user = User::find($request->get('users_id'));
        if (Moderator::hasAdmin($user->id)){
            return redirect()->back()->with('error', '用户'.$user->name.'已经添加过了');
        }
        if (!($user->roleFlag() & AdminFlag::ADMIN_FLAG_TOPIC_ED)){
            return redirect()->back()->with('error', '用户'.$user->name.'没有权限被添加');
        }
        Moderator::forceCreate(['uid' => $user->id, 'plate_id' => $request->get('plate_id')]);
        return redirect()->back()->with('success', '添加成功');
    }

    protected function errorAction(){
        return ['code' => 200, 'msg' => '错误操作'];
    }

    protected function platePullValidator(array $array){
        $rules = [
            'title'             => 'required|max:32',
            'display_name'      => 'required|max:64',
            'description'       => 'required|max:64',
            'img'               => 'file',
            'index'             => 'required|integer',
            'is_enable'         => 'max:3',
            'falg'              => 'required|integer'
        ];
        if (!empty($array['id'])){
            $rules['id'] = 'required|integer|exists:partitions,id';
        }
        return $rules;
    }
}
